<template>
  <!-- #ifndef H5 -->
  <u-navbar title="生产进度" fixed border leftIcon="" leftText=""></u-navbar>
  <!-- #endif -->
  <!-- #ifdef H5 -->
  <u-navbar title="生产进度" fixed border @leftClick="navigateBack" @rightClick="navigateHome">
    <template #right>
      <u-icon name="home" size="24"></u-icon>
    </template>
  </u-navbar>
  <!-- #endif -->
  <view class="page_wrap_container" :style="{ paddingTop: NavBarHeight + 'px' }">
    <view class="top_fixed_box" :style="{ top: NavBarHeight + 'px' }" v-if="orderStatus != '3'">
      <view class="top_fixed_box_main" @click="reportNum(pageDetails)">
        <view class="circle_icon"><up-icon name="plus" color="#42bac3"></up-icon></view>
        <text>汇报生产进度</text>
      </view>
    </view>
    <scroll-view
      :style="{ height: (orderStatus == '3' ? windowHeight : windowHeight - 80) + 'px', 'margin-top': orderStatus != '3' ? '92px' : '12px' }"
      scroll-y enable-flex :show-scrollbar="false" class="purchase_page_list">
      <view class="list_item_box" v-if="pageDetails?.purchaseProduceQtyVOList?.length > 0">
        <view class="liib_item_header_title">生产数量跟踪</view>
        <view class="liib_item_fk_wrap">
          <view class="liib_item_fk" v-for="(it, idx) in pageDetails?.purchaseProduceQtyVOList" :key="it.id">
            <view class="liib_item_real"
              v-if="pageDetails?.purchaseProduceQtyVOList?.length > 1 && expandFlag ? idx < 1 : true">
              <view class="liibi_main">
                <view class="text_header">
                  <view class="text_header_l">累计成品数：{{ it.totalProductQty || "-" }}</view>
                  <view class="text_header_r">{{ it.reportDate || "-" }}</view>
                </view>
                <view>备注：{{ it.remark || "-" }}</view>
              </view>
            </view>
          </view>
        </view>
        <view class="look_more" v-if="pageDetails?.purchaseProduceQtyVOList?.length > 1" @click="toggleFlagChange"
          :style="{ background: expandFlag ? 'linear-gradient(-180deg, rgba(255, 255, 255, 0) 0%, #fff 100%)' : '' }">
          {{ expandFlag ? '展开更多' : '收起' }}<u-icon color="inherit" size="14"
            :name="!expandFlag ? 'arrow-up' : 'arrow-down'"></u-icon>
        </view>
      </view>
      <view class="list_item_box">
        <view class="liib_item_header_title">生产时间跟踪</view>
        <view class="step_wrap">
          <up-steps dot direction="column" :current="stepList.length - 1" class="step_wrap_com">
            <up-steps-item v-for="(item, index) in stepList" :key="index">
              <template #desc>
                <view class="step_item">
                  <view class="step_item_label">{{ item.label }}</view>
                  <view class="step_item_time" v-if="pageDetails[item.key2]">{{
    pageDetails[item.key2] }}</view>
                  <view class="step_item_time" style="color:#42bac3" v-else
                    @click="showTimePicker(pageDetails[item.key2], item.key2)">点击选择时间
                  </view>
                </view>
              </template>
            </up-steps-item>
          </up-steps>
        </view>
      </view>
      <view :style="{ height: '50px'}"></view>
    </scroll-view>
    <up-popup :show="popupFormTimeShow" :round="10" @close="TimeFormClose" closeOnClickOverlay>
      <view class="status_wrap_pop">
        <view class="pop_actions">
          <view class="reset_btn" @click="TimeFormClose">关闭</view>
          <view class="confirm_btn" @click="popFormTimeSave">保存</view>
        </view>
        <view class="form_wrap">
          <up-form labelAlign="right" ref="TimeFormRef" :model="modalTime" labelWidth="130" :rules="formTimeRules">
            <up-form-item label="实际时间：" prop="Time.actualQualityTime" borderBottom>
              <up-cell :titleStyle="{ color: '#c1c4cc', fontSize: '15px' }" @click="handleShowDatePicker"
                :title="modalTime.Time.actualQualityTime" :isLink="true" arrow-direction="down"
                :border="false"></up-cell>
            </up-form-item>
          </up-form>
        </view>
      </view>
    </up-popup>
    <up-popup :show="popupFormShow" :round="10" @close="popFormClose" closeOnClickOverlay>
      <view class="status_wrap_pop">
        <view class="pop_actions">
          <view class="reset_btn" @click="popFormClose">关闭</view>
          <view class="confirm_btn" @click="popFormSave">保存</view>
        </view>
        <view class="form_wrap">
          <up-form labelAlign="right" ref="formReportRef" :model="modalReport" labelWidth="100" :rules="formRules">
            <up-form-item label="汇报日期：" prop="report.reportDate" borderBottom>
              <up-cell :titleStyle="{ color: '#c1c4cc', fontSize: '15px' }" @click="handleShowDatePicker"
                :title="modalReport.report.reportDate" :isLink="true" arrow-direction="down" :border="false"></up-cell>
            </up-form-item>
            <up-form-item label="累计成品数：" prop="report.totalProductQty" borderBottom>
              <up-input v-model="modalReport.report.totalProductQty" placeholder="请输入累计成品数"></up-input>
            </up-form-item>
            <up-form-item label="备注：" prop="report.remark" borderBottom>
              <up-textarea v-model="modalReport.report.remark" placeholder="请输入备注" height="40"
                maxlength="100"></up-textarea>
            </up-form-item>
          </up-form>
        </view>
      </view>
    </up-popup>
    <up-datetime-picker ref="datetimePickerRef" closeOnClickOverlay :show="datePickerShow" v-model="datetimeTime"
      mode="date" :formatter="formatter" @confirm="datePickerConfirm" @cancel="datePickerClose"
      @close="datePickerClose"></up-datetime-picker>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import HTTP from "@/utils/http"
import dayjs from "dayjs"
import { reactive } from "vue";
import type { PurchaseListType } from "./types"
import { onLoad } from "@dcloudio/uni-app";
import useScreenSize from "@/hooks/useScreenSize";
const { windowHeight, NavBarHeight, isIphoneX } = useScreenSize()
const navigateBack = () => {
  uni.navigateBack()
}
const navigateHome = () => {
  uni.switchTab({ url: "/pages/index/index" })
}
//获取页面 purchaseOrderCode
let purchaseOrderCode: string
let orderStatus: string
onLoad((options: any) => {
  purchaseOrderCode = options.purchaseOrderCode || ""
  orderStatus = options.status || ""
})
const pageDetails = ref<Record<string, any>>({})
const stepList = ref<any[]>([
  {
    id: '1',
    key1: 'fabricPlanTime',
    key2: 'fabricRealTime',
    label: '面料到厂',
    fabricPlanTime: '',
    fabricRealTime: '',
  },
  {
    id: '2',
    key1: 'sampleClothingPlanTime',
    key2: 'sampleClothingRealTime',
    label: '产前样',
    sampleClothingPlanTime: '',
    sampleClothingRealTime: '',
  },
  {
    id: '4',
    key1: 'productInspectPlanTime',
    key2: 'productInspectRealTime',
    label: '成品送检',
    productInspectPlanTime: '',
    productInspectRealTime: '',
  },
  {
    id: '5',
    key1: 'preMeetingPlanTime',
    key2: 'preMeetingRealTime',
    key3: 'preMeetingTimeList',
    label: '产前会',
    preMeetingPlanTime: '',
    preMeetingRealTime: '',
  },
  {
    id: '6',
    key1: 'publishPlanTime',
    key2: 'publishRealTime',
    label: '上线生产',
    publishPlanTime: '',
    publishRealTime: '',
  },
  {
    id: '7',
    key1: 'earlyInspectPlanTime',
    key2: 'earlyInspectRealTime',
    key3: 'earlyInspectTimeList',
    label: '初期查货',
    earlyInspectPlanTime: '',
    earlyInspectRealTime: '',
  },
  {
    id: '8',
    key1: 'middleInspectPlanTime',
    key2: 'middleInspectRealTime',
    key3: 'middleInspectTimeList',
    label: '中期查货',
    middleInspectPlanTime: '',
    middleInspectRealTime: '',
  },
  {
    id: '9',
    key1: 'offlinePlanTime',
    key2: 'offlineRealTime',
    label: '下线',
    offlinePlanTime: '',
    offlineRealTime: '',
  },
  {
    id: '10',
    key1: 'laterPlanTime',
    key2: 'laterRealTime',
    key3: 'laterTimeList',
    label: '尾查',
    laterPlanTime: '',
    laterRealTime: '',
  },
])
const showTimePicker = (item: any, key: string) => {
  if (item == null || item == undefined) {
    popupFormTimeShow.value = true
    currentInfo.value["key"] = key
  }
}
// 控制展开/折叠
const expandFlag = ref(true)
const toggleFlagChange = () => {
  expandFlag.value = !expandFlag.value
}
//DatePicker
const datetimeTime = ref(dayjs().format("YYYY-MM-DD"))
const datetimePickerRef = ref<any>(null);
const formatter = (type: string, value: string) => {
  if (type === 'year') {
    return `${value}年`;
  }
  if (type === 'month') {
    return `${value}月`;
  }
  if (type === 'day') {
    return `${value}日`;
  }
  return value;
};
const datePickerShow = ref(false)
const handleShowDatePicker = () => {
  datePickerShow.value = true
}
const datePickerConfirm = (event: any) => {
  datePickerShow.value = false
  datetimeTime.value = dayjs(event.value).format("YYYY-MM-DD")
  modalTime.Time.actualQualityTime = dayjs(event.value).format("YYYY-MM-DD")
  modalReport.report.reportDate = dayjs(event.value).format("YYYY-MM-DD")
}
const datePickerClose = () => {
  datePickerShow.value = false
  datetimeTime.value = dayjs().format("YYYY-MM-DD")
  modalTime.Time.actualQualityTime = dayjs().format("YYYY-MM-DD")
  modalReport.report.reportDate = dayjs().format("YYYY-MM-DD")
}
//popupFormTimeShow
const TimeFormRef = ref<any>(null)
const popupFormTimeShow = ref(false)
const TimeFormClose = () => {
  popupFormTimeShow.value = false
  TimeFormRef.value.resetFields()
  currentInfo.value = {}
  datetimeTime.value = dayjs().format("YYYY-MM-DD")
  modalTime.Time.actualQualityTime = dayjs().format("YYYY-MM-DD")
  modalReport.report.reportDate = dayjs().format("YYYY-MM-DD")
}
const popFormTimeSave = () => {
  const params = {
    ...pageDetails.value,
    [currentInfo.value["key"]]: modalTime.Time.actualQualityTime,
  }
  TimeFormRef.value.validate().then(() => {
    HTTP.POST({
      url: "sop/sop/purchase/produce/schedule/updateProduceSchedule",
      isJson: true,
      data: params,
      success: (res: any) => {
        if (res.code == 200) {
          uni.showToast({
            title: '操作成功',
            icon: 'none',
          })
          resetListData()
        }
      },
      complete: () => {
        TimeFormClose()
      }
    })
  })
}
//popupFormShow
const reportNum = (info: PurchaseListType) => {
  currentInfo.value = info
  popupFormShow.value = true
}
const modalReport = reactive({
  report: {
    reportDate: dayjs().format("YYYY-MM-DD"),
    totalProductQty: "",
    remark: ""
  }
})
const formRules = {
  'report.reportDate': { type: "string", required: true, message: "请选择汇报日期", },
  'report.totalProductQty': { type: "string", required: true, message: "请输入累计成品数", },
}
const formReportRef = ref<any>(null)
const popupFormShow = ref(false)
const popFormClose = () => {
  popupFormShow.value = false
  formReportRef.value.resetFields()
  datetimeTime.value = dayjs().format("YYYY-MM-DD")
  modalTime.Time.actualQualityTime = dayjs().format("YYYY-MM-DD")
  modalReport.report.reportDate = dayjs().format("YYYY-MM-DD")
}
const popFormSave = () => {
  formReportRef.value.validate().then((data: any) => {
    HTTP.POST({
      url: "sop/sop/purchase/produce/schedule/insert",
      isJson: true,
      data: { ...modalReport.report, purchaseOrderCode: currentInfo.value.purchaseOrderCode },
      success: (res: any) => {
        if (res.code == 200) {
          uni.showToast({
            title: '操作成功',
            icon: 'none',
          })
          getDetail()
        }
      },
      complete: () => {
        popFormClose()
      }
    })
  })
}
//search
const resetListData = () => {
  getDetail()
}
//列表数据
onMounted(() => {
  datetimePickerRef.value && datetimePickerRef.value?.setFormatter(formatter);
  getDetail()
})
const getDetail = async () => {
  HTTP.POST({
    url: "sop/sop/purchase/produce/schedule/getProduceSchedule",
    isJson: true,
    data: { purchaseOrderCode },
    success: (res: any) => {
      if (res.code == 200) {
        pageDetails.value = res.data
      }
    }
  })
}
// actions
const currentInfo = ref<Record<string, any>>({})
//form
const modalTime = reactive({
  Time: {
    actualQualityTime: dayjs().format("YYYY-MM-DD"),
  }
})
const formTimeRules = {
  'Time.actualQualityTime': { type: "string", required: true, message: "请选择实际时间", },
}
</script>
<style lang="scss" scoped>
.page_wrap_container {
  display: flex;
  flex-direction: column;
  position: relative;

  .top_fixed_box {
    position: absolute;
    top: 0;
    left: 0;
    height: 60px;
    line-height: 60px;
    width: 750rpx;
    margin: 24rpx auto;
    padding: 0 24rpx;
    z-index: 30;
    background-color: #f3f5f9;

    .top_fixed_box_main {
      background-color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 30rpx;
      gap: 8rpx;
      color: #42bac3;
      border-radius: 16rpx;
      box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.08);

      .circle_icon {
        border: 3rpx solid #42bac3;
        width: 36rpx;
        height: 36rpx;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }

  .purchase_page_list {
    background-color: #f3f5f9;

    .has_data_text {
      color: #aaa;
      text-align: center;
    }

    .list_item_box {
      background-color: #fff;
      position: relative;
      margin: 0 24rpx;
      border-radius: 16rpx;
      margin-bottom: 24rpx;

      .liib_item_header_title {
        font-size: 30rpx;
        font-weight: 500;
        height: 80rpx;
        line-height: 80rpx;
        padding-left: 24rpx;
        border-bottom: 1px solid #f1f2f3;
        color: $uni-color-primary;
      }

      .liib_item_fk_wrap {
        padding: 24rpx;
      }

      .liib_item_fk {
        display: flex;
        flex-direction: column;

        .liib_item_real {
          margin-bottom: 24rpx;
        }

        .liibi_main {
          display: flex;
          flex-direction: column;
          gap: 12rpx;
          color: #444;

          .text_header {
            display: flex;
            align-items: center;

            .text_header_l {
              width: 380rpx;
            }

            .text_header_r {
              flex: 1;
            }
          }
        }
      }

      .look_more {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        font-size: 28rpx;
        color: $uni-color-primary;
        margin-right: 4rpx;
        position: absolute;
        left: 0;
        right: 0;
        bottom: 16rpx;
        padding-top: 100rpx;
      }

      .step_wrap {
        padding: 24rpx;

        .step_item {
          display: flex;
          align-items: center;
          flex-wrap: wrap;

          .step_item_label {
            min-width: 200rpx;
          }

          .step_item_time {
            color: #666;
            font-size: 26rpx;
          }
        }
      }
    }

  }

  .empty_wrap {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
}

.status_wrap_pop {
  padding: 30rpx;
  min-height: 300rpx;

  .form_wrap {
    width: 100%;
    padding: 24rpx 30rpx;
  }

  .pop_actions {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .reset_btn {
      color: #888;
      padding: 12rpx;
    }

    .confirm_btn {
      color: $uni-color-primary;
      padding: 12rpx;
    }
  }

  .status_item {
    .status_item_title {
      padding: 30rpx 0;
      font-size: 36rpx;
      font-weight: 400;
      color: #333;
    }

    .status_item_btns_box {
      display: flex;
      flex-wrap: wrap;
      gap: 18rpx;

      .status_item_btn {
        border: 1px solid #ddd;
        padding: 10rpx 20rpx;
        color: #666;
      }

      .status_item_btn_active {
        border: 1px solid $uni-color-primary;
        background-color: $uni-color-primary;
        color: #fff;
      }
    }
  }
}
</style>
<style>
.step_wrap .u-steps-item {
  padding: 20rpx 0 !important;
}
</style>